#region License
// TagService.cs
// 
// Copyright (c) 2012 Xoqal.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

namespace Kaqaz.Services
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Xoqal.Data;

    public class TagService : ITagService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly Data.ITagRepository tagRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="TagService" /> class.
        /// </summary>
        /// <param name="unitOfWork">The unit of work.</param>
        public TagService(IUnitOfWork unitOfWork, Data.ITagRepository tagRepository)
        {
            this.unitOfWork = unitOfWork;
            this.tagRepository = tagRepository;
        }

        /// <summary>
        /// Gets the splited tags.
        /// </summary>
        /// <param name="tag">The tag.</param>
        /// <returns></returns>
        public static string[] GetSplitedTags(string tag)
        {
            var tags = tag.Split(',', ';', '،').Select(t => t.Trim());
            return tags.ToArray();
        }

        /// <summary>
        /// Gets the tags. 
        /// </summary>
        /// <remarks>
        /// It parses the Tags property and create a list of Entity.Tag objects using the TagRepository.GetOrInsert method.
        /// </remarks>
        /// <returns></returns>
        public IEnumerable<Entities.Tag> GetTags(string tags)
        {
            if (string.IsNullOrWhiteSpace(tags))
            {
                return Enumerable.Empty<Entities.Tag>().ToList();
            }

            List<Entities.Tag> tagEntites = new List<Entities.Tag>();

            var splited = TagService.GetSplitedTags(tags);
            foreach (string tagName in splited)
            {
                tagEntites.Add(this.tagRepository.GetOrInsert(tagName.Trim()));
            }

            return tagEntites;
        }
    }
}
